package com.sensoro.beacon.test;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.sensoro.beacon.kit.Beacon;
import com.sensoro.beacon.kit.BeaconConfiguration;
import com.sensoro.beacon.kit.BeaconManagerListener;
import com.sensoro.beacon.kit.SensoroBeaconFlowConnection;
import com.sensoro.beacon.kit.SensoroBeaconFlowConnection.BeaconFlowConnectionCallback;
import com.sensoro.beacon.kit.SensoroBeaconFlowConnection.BeaconFlowSettingCallback;
import com.sensoro.beacon.kit.SensoroBeaconFlowConnection.SensoroException;
import com.sensoro.beacon.kit.SensoroBeaconManager;

public class MainActivity extends Activity implements BeaconManagerListener {
	SensoroBeaconManager beaconManger;
	boolean connFinish = false;
	SensoroBeaconFlowConnection conn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		beaconManger = SensoroBeaconManager.getInstance(this);
		beaconManger.setBeaconManagerListener(this);
		try {
			beaconManger.startService();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onNewBeacon(Beacon beacon) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGoneBeacon(Beacon beacon) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpdateBeacon(ArrayList<Beacon> beacons) {
		for (int i = 0; i < beacons.size(); i++) {
			if (!beacons.get(i).getSerialNumber().equals("0117C55791BC")) {
				beacons.remove(i);
				i--;
			}
		}
		if (beacons.size() == 1) {
			try {
				conn = new SensoroBeaconFlowConnection(this, beacons.get(0), new MyBeaconConnectionCallback());
				if (!connFinish) {
					conn.connect();
				}
			} catch (SensoroException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	class myBeaconSettingCallback implements BeaconFlowSettingCallback {

		@Override
		public void onSettingState(Beacon beacon, int errorCode) {

		}
	}

	class MyBeaconConnectionCallback implements BeaconFlowConnectionCallback {

		@Override
		public void onConnectedState(Beacon beacon, int newState, int status) {
			if (newState == Beacon.CONNECTED && status == SensoroBeaconFlowConnection.SUCCESS) {
				Log.e("lfr", "connected");
				connFinish = true;

				BeaconConfiguration beacon2 = null;
				try {
					beacon2 = new BeaconConfiguration.Builder().setMajor(10001).setMinor(10002).setUuid("FDA50693_A4E2_4FB1_AFCF_C6EB07647825").creat();
				} catch (Exception e) {
					e.printStackTrace();
				}
				conn.setBeaconConfiguration(beacon2, new myBeaconSettingCallback());
			}
		}
	}

	@Override
	protected void onDestroy() {
		beaconManger.stopService();
		super.onDestroy();
	}
}
